package com.huilink.webmail.service.impl;

import java.util.List;
import java.util.concurrent.Executor;

import org.apache.commons.mail.Email;

import com.huilink.db.dbo.AdminMailSettingDbo;
import com.huilink.safethread.ExceptionListener;
import com.huilink.safethread.SafeRunnable;
import com.huilink.webmail.service.api.MailSender;
import com.huilink.webmail.service.api.ResponseCallback;

public class MailSenderImpl implements MailSender {

	private Executor executor;
	
	private Email emailService;
	
	private AdminMailSettingDbo adminMailSetting;
	
	private ExceptionListener exceptionListener;
	 
	private ResponseCallback callback;
	
	public MailSenderImpl(Executor executor, Email emailService,
			AdminMailSettingDbo adminMailSetting) {
		this.executor =  executor;
		this.emailService = emailService;
		this.adminMailSetting =  adminMailSetting;
	}
	
	public void sendMail(String subject, String emailBody,
			List<String> toAddressList, List<String> ccAddressList,
			ResponseCallback callback) {
		exceptionListener = new WebMailExecptionListener();
		this.callback =callback;
		FireSendMail fire = new FireSendMail(subject, emailBody, toAddressList,
				ccAddressList);
		executor.execute(fire);
	}
	
	private class FireSendMail extends SafeRunnable{
		private String subject;
		private String emailBody;
		private List<String> toAddressList;
		private List<String> ccAddressList;
	
		public FireSendMail(String subject, String emailBody,
				List<String> toAddressList, List<String> ccAddressList) {
			// use email subject as id
			super(executor, exceptionListener, subject);
			this.subject = subject;
			this.emailBody = emailBody;
			this.toAddressList = toAddressList;
			this.ccAddressList = ccAddressList;
		}

		@Override
		protected void runImpl() throws Throwable {
			emailService.setHostName(adminMailSetting.getSmtpHost());
			emailService.setFrom(adminMailSetting.getFromAddress(),
					adminMailSetting.getFromName());
			for (String toAddress : toAddressList) {
				emailService.addTo(toAddress);
			}
			for (String ccAddress : ccAddressList) {
				emailService.addCc(ccAddress);
			}
			emailService.setSubject(subject);
			emailService.setMsg(emailBody);
			emailService.send();
			
			callback.success(null);
		}
		
	}
	
	private class WebMailExecptionListener implements ExceptionListener {
		 
		public void fireFailure(Throwable arg0, Object arg1) {
			callback.failure(arg0, (String)arg1);
		}

	}

}
